<template>
  <a-upload
    :action="actions"
    :headers="headers"
    :data="data1"
    @before-upload="beforeUpload"
    :show-file-list="false"
    @success="success"
    @error="error"
  >
    <template #upload-button>
      <a-button
        type="primary"
        style='user-select: none;'
      >
        <template #icon>
          <icon-upload />
        </template>
        <slot></slot>
      </a-button>
    </template>
  </a-upload>
</template>

<script lang="ts" setup>
import { computed, onMounted, defineEmits, defineProps } from "vue";
import { Message } from "@arco-design/web-vue";
import {getBaseURL} from "@/utils";

// 定义 props
const props = defineProps({
  actions: {
    type: String,
    required: true,
  },
  data1: {
    type: Object,
    required: true,
  },
});

// 定义 emits
const emit = defineEmits(["getList"]);

// 计算属性 headers 和 data1
const headers = {
  token: localStorage.getItem("token")!,
};

const data1 = computed(() => props.data1);

const actions = computed(() => {
  return getBaseURL() + props.actions;
});

// 上传文件前的验证
const beforeUpload = (file: any) => {
  const isExcel = [
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  ].includes(file.type);
  if (!isExcel) {
    Message.error("只能上传 Excel 文件!");
    return false; // 阻止上传
  }
  return true; // 允许上传
};

// 上传成功后
const success = (options: { file: any; event?: ProgressEvent }) => {
  const res = options.response;

  if (res.code === 200) {
    Message.success(res.msg);
  } else {
    if (res.data) {
      // if (res.data !== null) {
      if (res.data.errors) {
        return Message.error(JSON.stringify(res.data.errors));
      }
      Message.warning(res.msg);
    }else{
      Message.warning(res.msg);
    }
    // } else {
    //   Message.warning(res.msg);
    // }
    // } else {
    //   Message.warning(res.msg);
    // }
  }
  emit("getList");
  return false;
};

const error = () => {

};

onMounted(() => {});
</script>

<style>
</style>
